package com.qf.automation.file.service.impl;


import com.qf.automation.file.controller.FileController;
import com.qf.automation.file.dao.GifWorkDao;
import com.qf.automation.file.model.GifWork;
import com.qf.automation.file.model.GifWorkExample;
import com.qf.automation.file.service.FileService;
import com.qf.automation.file.service.GifService;
import com.qf.automation.file.utils.GifUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Service
public class GifServiceImpl implements GifService {
    @Resource
    FileService fileService;
    @Resource
    GifWorkDao gifWorkDao;
//    创建gif和gif文件,并且存放到数据库
    @Override
    public void craeteGif(int count,File file,String fileName,String url)  {
        try {
            GifUtil.buildGif(file.getAbsolutePath(), 5, 50, 10, 2);
            String jpgFileName=fileName.substring(0,(fileName.lastIndexOf(".")))+".jpg";
            String gipFileName=fileName.substring(0,(fileName.lastIndexOf(".")))+".gif";

            String jpgUrl = fileService.saveFile(new File(FileController.FILE_PATH+File.separator+jpgFileName),jpgFileName);
            String gifUrl = fileService.saveFile(new File(FileController.FILE_PATH+File.separator+gipFileName),gipFileName);
            //保存jpgurl与gifurl至数据库
            //更新的条件就是url
            GifWorkExample example=new GifWorkExample();
            GifWorkExample.Criteria criteria = example.createCriteria();
            criteria.andUrlEqualTo(url);
            /* 写入jpgurl与gifurl与1 */
            GifWork gifWork=new GifWork();
//            gifWork.setId(count);
            gifWork.setJpgUrl(jpgUrl);
            gifWork.setGifUrl(gifUrl);
            gifWork.setState(1);
            gifWorkDao.updateByExampleSelective(gifWork,example);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
//保存大的url地址
    @Override
    public int saveFileUrl(String url) {
        GifWork gifWork=new GifWork();
        gifWork.setUrl(url);
        gifWork.setState(0);
        return gifWorkDao.insertSelective(gifWork);
    }

    @Override
    public GifWork selectByUrl(String url) {
        GifWorkExample example=new GifWorkExample();
        GifWorkExample.Criteria criteria = example.createCriteria();
        criteria.andGifUrlEqualTo(url);
        List<GifWork> gifWorks = gifWorkDao.selectByExample(example);
        if (gifWorks!=null&&gifWorks.size()>0){
            return gifWorks.get(0);
        }else {
            return null;
        }
    }

}
